<?php

class FirmsController extends Controller
{

	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/admin';


	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}


	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('index','create','update','delete','saveall'),
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}


	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Firms;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Firms']))
		{
			$model->attributes=$_POST['Firms'];
			if($model->save())
			{
				$this->uploadFiles( $model->id );
				
				if($_POST['save_exit']) {
					$this->redirect(array('index'));
				}
				if($_POST['save'])
				{					
					$this->redirect(array('update', 'id'=>$model->id ));
				}
			}
		}		

		$this->render('create',array(
			'model'=>$model,
		));
	}


	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		$errors = $this->uploadFiles( $id );
		
		if($_POST['delete_attach']) {
			$id_attach = $_POST['id_delete_attach'];
			if ($id_attach) {
				$attach = Uploads::model()->findByPk( $id_attach );
				@unlink('uploads/' . $attach->file_name);

				Uploads::model()->deleteByPk( $id_attach );

				if ( $model->id_icon == $id_attach ) {
					$model->id_icon = 0;					
				}
			}
		} elseif($_POST['set_icon']) {
			$model->id_icon = $_POST['id_icon_attach'];		
		}

		// save images description
		if ($_POST['alt']) {
			foreach ($_POST['alt'] as $k => $v) {

				if ($k != $_POST['id_delete_attach']) {
					$attach = Uploads::model()->findByPk($k);
					$attach->alt = htmlspecialchars($v);
					$attach->save();
				}
			}
		}

		$model->attributes=$_POST['Firms'];

		// parse images
		$patterns = array();
		$replacements = array();
		//$patterns[] = '/img/';
		foreach ($model->uploads as $image) {			
			//$patterns[] = '/<img src="(.*?)\/uploads\/' . $image->file_name . '"\s*(alt="(.*?)")>/i';
			$patterns[] = '/uploads\/' . $image->file_name . '"\s*(alt="(.*?)")?/i';
			//$replacements[] = '<img src="' . Yii::app()->request->getBaseUrl(true) . '/uploads/' . $image->file_name . '" alt="'.$image->alt.'">';
			$replacements[] = 'uploads/' . $image->file_name . '" alt="'.$image->alt.'"';
		}		
		$model->post = preg_replace($patterns, $replacements, $model->post);

		// save model
		if($model->save()) {
			if($_POST['save_exit']) {
				$this->redirect(array('index'));
			}
		}

		$this->render('update',array(
			'model'=>$model,
			'errors'=>$errors,
		));
	}


	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request

			$model = $this->loadModel($id);

			// delete uploads
			foreach ($model->uploads as $attach) {
				@unlink('uploads/' . $attach->file_name);
				Uploads::model()->deleteByPk( $attach->id );
			}				

			// delete firm
			$model->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	
	/**
	 * save all models
	 */
	public function actionSaveall()
	{
		foreach ( $_POST['item'] as $k => $item )
		{
			$model=$this->loadModel($k);

			$model->order_id = $item['order'];
			$model->enabled = $item['enabled'] ? $item['enabled'] : 0;

			$model->save();
		}

		$this->redirect(array('index'));
	}


	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$model=new Firms('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Firms']))
			$model->attributes=$_GET['Firms'];

		$this->render('index', array(
			'model'=>$model,
		));
	}


	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Firms::model()->findByPk((int)$id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}


	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='firms-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}


	protected function uploadFiles( $id_owner )
	{
		$errors = array();
		if ($_FILES) {
			foreach ( $_FILES['upload']['name'] as $k => $file )
			{
				if (is_uploaded_file($_FILES['upload']['tmp_name'][$k]))
				{
					$attach = new Uploads();
					$attach->owner_type = 'FIRM';
					$attach->id_owner = $id_owner;
					$attach->upload_date = time();
					$attach->original_name = $_FILES['upload']['name'][$k];
					$attach->file_name = $attach->owner_type . '_' . $attach->id_owner . '_' . substr( md5(time()+rand()), 0, 10 );
					$attach->filesize = $_FILES['upload']['size'][$k];

					$tmp = getimagesize( $_FILES['upload']['tmp_name'][$k] );
					if ( $tmp )
					{
						// 1 = GIF, 2 = JPG, 3 = PNG, 4 = SWF, 5 = PSD, 6 = BMP,
						// 7 = TIFF(intel), 8 = TIFF(motorola), 9 = JPC, 10 = JP2, 11 = JPX
						switch ($tmp[2]) {
							case 1: $ext = 'gif'; break;
							case 2: $ext = 'jpg'; break;
							case 3: $ext = 'png'; break;
							case 6: $ext = 'bmp'; break;
							default : $ext = null; break;
						}
						$attach->file_name .= '.' . $ext;
						$attach->is_image = 1;
						$attach->width = $tmp[0];
						$attach->height = $tmp[1];

						if ( $ext && @move_uploaded_file($_FILES['upload']['tmp_name'][$k], "uploads/".$attach->file_name))
						{
							if ( !$attach->save() ){
								$errors[] = $_FILES['upload']['name'][$k];
							}
						} else {
							$errors[] = $_FILES['upload']['name'][$k];
						}
					} else {
						$errors[] = $_FILES['upload']['name'][$k];
					}
				}
			}
		}
	}

	
}
